<template>
  <common-form
    :form="form"
    ref="form"
    class="form"
    @selectChange="selectChange"
    :formData="formData"
    labelPosition="top"
    :type="editType"
    :rules="rules"
  >
    <!--提示-->
    <div slot="relevance" class="prompt">
      {{ $t('configLazyLoad.businessConfig.fieldTip7') }}
    </div>
    <!--提示-->
    <div slot="importantField" class="prompt">{{ $t('configLazyLoad.businessConfig.fieldTip11') }}</div>
  </common-form>
</template>

<script>
import commonForm from '../base/commonForm'
import { deepClone } from '@/utils/m7Utils'
import { checkform } from '@/utils/validate'
const baseForm = {
  name: '',
  required: 'no',
  show: 'no',
  relevance: 'no',
  type: 'single',
  dic: '',
  trigger: '', // manual or phoneAddress
  default: '',
  requireType: '',
  enable: 'yes',
  prompt: '',
  importantField: 'false'
}
export default {
  name: 'base-info',
  props: {
    custFieldsList: {
      type: Array,
      defautl: function () {
        return []
      }
    }
  },
  inject: ['busType'],
  data() {
    let validate1 = (rule, value, callback) => {
      if (this.form.type !== 'number') {
        callback()
      }
      if (value === '' || !checkform(value, 'Number') || !checkform(value, 'Double')) {
        callback()
      } else {
        callback(new Error(this.$t('customer.shouldBeNumber')))
      }
    }
    return {
      editType: '', // 是否编辑字段
      form: deepClone(baseForm),
      formData: [],
      formDataBase: [
        { label: this.$t('configLazyLoad.questionnaireConfig.fieldName'), name: 'name', type: 'input' },
        {
          label: this.$t('config.customer.whetherNecessary'),
          name: 'required',
          type: 'switch',
          data: ['required', 'no']
        },
        {
          label: this.$t('configLazyLoad.businessConfig.associateCustomerInformation'),
          name: 'relevance',
          type: 'select',
          data: this.custFieldsList
        },
        { label: this.$t('configLazyLoad.businessConfig.fieldsType'), name: 'type', type: 'select', data: [] },
        {
          label: this.$t('configLazyLoad.businessConfig.importantFieldMarker'),
          name: 'importantField',
          type: 'switch',
          data: ['true', 'false']
        }
      ], // 基本表单
      formDataDic: [
        { label: this.$t('configLazyLoad.businessConfig.associateDictionary'), name: 'dic', type: 'select', data: [] }
      ],
      formDataTrigger: [
        {
          label: this.$t('configLazyLoad.businessConfig.triggerFillingCondition'),
          name: 'trigger',
          type: 'select',
          data: [
            { label: '手动', value: 'manual' },
            { label: '客户电话归属地', value: 'phoneAddress' }
          ]
        }
      ],
      dicDefault: [
        { label: this.$t('configLazyLoad.businessConfig.defaultValue'), name: 'default', type: 'select', data: [] }
      ], // 可选表单（有字典时用到）
      noDicDefault: [
        {
          label: this.$t('configLazyLoad.businessConfig.defaultValue'),
          name: 'default',
          type: 'input',
          subType: '',
          data: []
        }
      ], // 可选表单（无字典时用到）
      promptText: [
        {
          label: this.$t('configLazyLoad.businessConfig.promptText'),
          name: 'prompt',
          type: 'input',
          subType: '',
          data: []
        }
      ],
      noDefault: [], // 附件用到
      options: [],
      rules: {
        name: [{ required: true, message: this.$t('validate.required'), trigger: 'blur' }],
        type: [{ required: true, message: this.$t('validate.required'), trigger: 'change' }],
        dic: [{ required: true, message: this.$t('validate.required'), trigger: 'change' }],
        trigger: [{ required: true, message: this.$t('validate.required'), trigger: 'change' }],
        default: [{ required: false, validator: validate1, trigger: 'blur' }],
        prompt: [{ max: 20, message: this.$t('validate.maxLength20'), trigger: 'blur' }]
      },
      dialogObj: {
        visible: false,
        title: this.$t('configLazyLoad.businessConfig.newAction'),
        type: 'actionInfo',
        width: '840px'
      },
      types: {
        input: ['single', 'number'],
        textarea: ['multi'],
        select: ['radio', 'dropdownTree', 'dropdown', 'checkbox'],
        date: ['date', 'datetime'],
        time: ['time'],
        empty: ['file']
      },
      custType: {
        radio: ['radio', 'dropdownTree', 'dropdown'],
        dropdown: ['dropdownTree', 'dropdown'],
        checkbox: ['checkbox']
      },
      businessFieldType: [],
      provinceDic: '', // 省市县字典id
      selectType: ''
    }
  },
  computed: {},
  components: {
    commonForm
  },
  watch: {
    custFieldsList() {
      this.formDataBase.forEach((item) => {
        if (item.name === 'relevance') {
          item.data = this.custFieldsList
        }
      })
    }
  },
  methods: {
    /*
     * 下拉框change函数
     * @param data.name 变化的字段名称
     * @param data.value 变化字段值
     * */
    selectChange({ name, value }) {
      if (name === 'type') {
        this.typeChange(value, this.form)
      } else if (name === 'dic') {
        this.dicChange(value, {})
      } else if (name === 'relevance') {
        this.form.dic = ''
        this.form.type = 'single'
        this.relevanceChange(value)
      } else if (name === 'required') {
        this.showDicRequiredType()
      }
    },
    // 是否加载字典必填级选择
    showDicRequiredType() {
      let last = this.formData[this.formData.length - 1]
      if (last && last.name === 'requireType') {
        this.formData.pop()
      }
      if (this.form.required !== 'required' || this.form.type !== 'dropdown') {
        return
      }
      if (!this.form.dic) {
        return
      }
      this.$store.dispatch('getCache', { type: 'options' }).then((options) => {
        let current = options.find((item) => {
          return item._id === this.form.dic
        })
        if (!current || (current && current.cascade < 2)) {
          return
        }
        let arr = [{ label: this.$t('configLazyLoad.businessConfig.allRequired'), value: '' }]
        for (let i = 1; i < current.cascade; i++) {
          arr.push({ label: i + this.$t('configLazyLoad.businessConfig.levelRequired'), value: i })
        }
        this.formData.push({
          label: this.$t('configLazyLoad.businessConfig.dictionaryLevelSelection'),
          name: 'requireType',
          type: 'select',
          data: arr
        })
        if (this.form.requireType && this.form.requireType >= arr.length) {
          this.form.requireType = ''
        }
      })
    },
    relevanceChange(value) {
      if (value === 'no') {
        this.formDataBase.forEach((item) => {
          if (item.name === 'type') {
            item.data = this.businessFieldType
          }
        })
        this.typeChange(this.form.type, this.form)
      } else {
        this.relevanceTypeChange(this.form.relevance, { dic: this.form.dic })
      }
    },
    relevanceTypeChange(value) {
      let type = ''
      this.form.dic = ''
      this.custFieldsList.some((item) => {
        if (item.value === value) {
          type = item.type
          this.form.dic = value === 'stable_province' ? this.provinceDic : item.dicId || ''
          return true
        }
      })
      if (!type) {
        this.form.relevance = 'no'
        this.selectChange({ name: 'relevance', value: 'no' })
        this.$message.error(this.$t('configLazyLoad.businessConfig.fieldTip9'))
        return
      }
      let list = this.businessFieldType.filter((item) => {
        if (item.value === 'single' || item.value === 'multi') {
          return true
        } else if (type === 'radio') {
          return this.custType.radio.indexOf(item.value) !== -1
        } else if (type === 'checkbox') {
          return this.custType.checkbox.indexOf(item.value) !== -1
        } else if (type === 'dropdown') {
          return this.custType.dropdown.indexOf(item.value) !== -1
        }
      })
      // 字段类型里与form中不匹配，重置form
      if (!list.some((item) => item.value === this.form.type)) {
        this.$message.error(this.$t('configLazyLoad.businessConfig.fieldTip8'))
        this.form.type = 'single'
      }
      this.formDataBase.forEach((item) => {
        if (item.name === 'type') {
          item.data = list
        }
      })
      this.showDicRequiredType()
      this.formData = [...this.formDataBase]
      this.form.default = ''
      this.form.prompt = ''
      this.form.trigger = ''
    },
    /*
     * 字典变化
     * @param {String} value 字典id
     * @param {Object} data 回显表单数据
     * */
    dicChange(value, data) {
      this.dicDefault[0].data = []
      this.form.default = (data && data.default) || ''
      this.form.prompt = (data && data.prompt) || ''
      this.form.trigger = (data && data.trigger) || 'manual'
      let dicName = ''
      if (value) {
        this.formDataDic[0].data.some((item) => {
          if (value === item.value) {
            this.dicDefault[0].data = item.options.map((one) => {
              return { value: one.key, label: one.name }
            })
            this.dicDefault[0].data.unshift({ label: '无', value: '' })
            dicName = item.label
            return true
          }
        })
      }
      if (dicName === '省市县' && (this.form.type === 'dropdown' || this.form.type === 'dropdownTree')) {
        this.formData = [].concat(this.formDataBase, this.formDataDic, this.formDataTrigger, this.dicDefault)
      } else {
        this.formData = [].concat(this.formDataBase, this.formDataDic, this.dicDefault)
      }
      if (this.selectType !== 'checkbox' && this.selectType !== 'radio') {
        this.formData = [].concat(this.formData, this.promptText)
      }
      this.showDicRequiredType()
    },
    /*
     * 字段类型变化
     * @param {String} value 字段类型
     * @param {Object} data 回显表单数据
     * */
    async typeChange(value, data) {
      if (data.relevance && data.relevance !== 'no') {
        this.showDicRequiredType()
        return
      }
      let type = 'input'
      let subType = ''
      for (let i in this.types) {
        if (this.types[i].indexOf(value) !== -1) {
          type = i
          if (type.indexOf('date') !== -1) {
            subType = value
          }
          break
        }
      }
      this.selectType = value
      if (type === 'select') {
        // 需要展示字典和默认值
        await this.$store.dispatch('getCache', { type: 'options' }).then((options) => {
          this.options = options.map((item) => {
            return { cascade: item.cascade, value: item._id, label: item.name, options: item.options || [] }
          })
          this.formDataDic[0].data = this.options
          this.dicChange(data.dic, data, value)
        })
      } else if (type === 'empty') {
        // 不需要展示字典和默认值
        this.formData = [...this.formDataBase]
        this.form.default = ''
        this.form.prompt = ''
        this.form.dic = ''
        this.form.trigger = ''
      } else {
        // 只需要展示默认值
        if (subType) {
          this.noDicDefault[0].subType = subType
        }
        this.noDicDefault[0].type = type
        this.formData = [].concat(this.formDataBase, this.promptText, this.noDicDefault)
        this.form.default = data && data.default ? data.default : ''
        this.form.prompt = data && data.prompt ? data.prompt : ''
        this.form.trigger = ''
        this.form.dic = ''
      }
    },
    create() {
      let data = this.$refs.form.submit()
      return data
    },
    // 回显
    initData(type, data) {
      this.form = deepClone(baseForm)
      this.editType = ''
      if (type === 'edit') {
        this.editType = 'edit'
        for (let i in this.form) {
          this.form[i] = data[i] || this.form[i]
        }
      }
      this.relevanceChange(this.form.relevance)
      this.$refs.form.clearValidate()
    }
  },
  beforeMount() {
    this.$store.dispatch('getCache', { type: 'businessFieldType' }).then((res) => {
      let list = res.map((item) => {
        return { label: item.code_name, value: item.code_value }
      })
      this.businessFieldType = list
      this.formDataBase.forEach((item) => {
        if (item.name === 'type') {
          item.data = this.businessFieldType
        }
      })
    })
    this.$store.dispatch('getCache', { type: 'options' }).then((options) => {
      options.some((item) => {
        if (item.accountId === 'system' && item.name === '省市县') {
          this.provinceDic = item._id
        }
      })
    })
  }
}
</script>

<style scoped lang="stylus">
@import '../../../../../assets/common.styl'
.prompt
  color $c-prompt
  font-size 12px
  line-height 16px
</style>
